<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\tools\Curl;
use app\tools\Wechat;
use app\models\Customer;

class WechatController extends BaseController
{
  	//小程序送审配置
  	public function actionXcxAudit() {
    	$is_audit = Yii::$app->params['is_audit'];
    	return Re::data(['data' => $is_audit]);
  	}

  	//获取小程序openid
  	public function actionGetOpenid() {
		$code = Yii::$app->request->post('code', '');
		$res = $this->getOpenid($code);//获取小程序openid
		$res = json_decode($res);
		if ($res->errcode != 0) {
			return Re::data(null, $res->errmsg, Re::ERROR);
		}
		$customer_info = Customer::find()->where(['openid' => $res->openid])->one();
		if (!$customer_info) {
			$customer_info = new Customer();
			$customer_info->nickname = '微信用户';
			$customer_info->openid = $res->openid;
			$customer_info->icon = Yii::$app->params['avator'];
			$customer_info->created_at = time();
			if (!$customer_info->save()) {
				return Re::data(null, $customer_info->showErrors(), Re::ERROR);
			}
		}
		return Re::data(['data' => $customer_info]);
	}

	//获取小程序用户手机号
	public function actionGetPhone() {
		$code = Yii::$app->request->post('code', '');
		$res = $this->getPhone($code);
		$res = json_decode($res);
		if ($res->errcode != 0) {
			return Re::data(null, $res->errmsg, Re::ERROR);
		}
		return Re::data(['data' => $res->phone_info->phoneNumber]);
	}

  	private function getOpenid($code) {
		$appid =  Yii::$app->params['wechatConfig']['app_id'];
		$appsecret = Yii::$app->params['wechatConfig']['secret'];
		$response = Curl::curl_get("https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code");
		return $response;
  	}

	private function getPhone($code) {
		$access_token = Wechat::getAccessToken();
		$data = [
			'code' => $code
		];
		$response = Curl::curl_post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$access_token", json_encode($data,JSON_UNESCAPED_UNICODE));
		return $response;
	}
}
